package mylego

import (
	"crypto"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"errors"
	"github.com/go-acme/lego/v4/certcrypto"
	"github.com/go-acme/lego/v4/certificate"
	"github.com/go-acme/lego/v4/challenge/http01"
	"github.com/go-acme/lego/v4/challenge/tlsalpn01"
	"github.com/go-acme/lego/v4/lego"
	"github.com/go-acme/lego/v4/providers/dns/alidns"
	"github.com/go-acme/lego/v4/registration"
	"os"
)

type LegoData struct {
	legoConfig  *lego.Config
	myUser      MyUser
	HasGetCerts bool
	CertPath    string
	KeyPath     string
}

func (this *LegoData) InitLego(email string) error {
	privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return err
	}

	this.myUser = MyUser{
		Email: email,
		key:   privateKey,
	}
	this.legoConfig = lego.NewConfig(&this.myUser)
	this.legoConfig.CADirURL = lego.LEDirectoryProduction
	this.legoConfig.Certificate.KeyType = certcrypto.RSA2048
	return nil
}

type MyUser struct {
	Email        string
	Registration *registration.Resource
	key          crypto.PrivateKey
}

func (u *MyUser) GetEmail() string {
	return u.Email
}
func (u MyUser) GetRegistration() *registration.Resource {
	return u.Registration
}
func (u *MyUser) GetPrivateKey() crypto.PrivateKey {
	return u.key
}

func (this *LegoData) GetCertsByHttp(domain string, port string) (*certificate.Resource, error) {
	if this.legoConfig == nil {
		return nil, errors.New("请先调用 InitLego")
	}
	// Create a user. New accounts need an email and private key to start.

	// This CA URL is configured for a local dev instance of Boulder running in Docker in a VM.
	//config.CADirURL = "http://192.168.99.100:4000/directory"
	//config.CADirURL = lego.LEDirectoryStaging
	this.legoConfig.CADirURL = lego.LEDirectoryProduction
	this.legoConfig.Certificate.KeyType = certcrypto.RSA2048

	// A client facilitates communication with the CA server.
	client, err := lego.NewClient(this.legoConfig)
	if err != nil {
		return nil, err
	}

	// We specify an HTTP port of 5002 and an TLS port of 5001 on all interfaces
	// because we aren't running as root and can't bind a listener to port 80 and 443
	// (used later when we attempt to pass challenges). Keep in mind that you still
	// need to proxy challenge traffic to port 5002 and 5001.
	err = client.Challenge.SetHTTP01Provider(http01.NewProviderServer("", port))
	if err != nil {
		return nil, err
	}

	// New users will need to register
	reg, err := client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
	if err != nil {
		return nil, err
	}
	this.myUser.Registration = reg

	request := certificate.ObtainRequest{
		Domains: []string{domain},
		Bundle:  true,
	}
	certificates, err := client.Certificate.Obtain(request)
	if err != nil {
		return nil, err
	}
	this.HasGetCerts = true
	return certificates, nil
}

func (this *LegoData) GetCertsByHttps(domain string, port string) (*certificate.Resource, error) {
	if this.legoConfig == nil {
		return nil, errors.New("请先调用 InitLego")
	}
	// Create a user. New accounts need an email and private key to start.

	// This CA URL is configured for a local dev instance of Boulder running in Docker in a VM.
	//config.CADirURL = "http://192.168.99.100:4000/directory"
	//config.CADirURL = lego.LEDirectoryStaging
	this.legoConfig.CADirURL = lego.LEDirectoryProduction
	this.legoConfig.Certificate.KeyType = certcrypto.RSA2048

	// A client facilitates communication with the CA server.
	client, err := lego.NewClient(this.legoConfig)
	if err != nil {
		return nil, err
	}

	err = client.Challenge.SetTLSALPN01Provider(tlsalpn01.NewProviderServer("", port))
	if err != nil {
		return nil, err
	}

	// New users will need to register
	reg, err := client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
	if err != nil {
		return nil, err
	}
	this.myUser.Registration = reg

	request := certificate.ObtainRequest{
		Domains: []string{domain},
		Bundle:  true,
	}
	certificates, err := client.Certificate.Obtain(request)
	if err != nil {
		return nil, err
	}
	this.HasGetCerts = true
	return certificates, nil
}

func (this *LegoData) ReNew(domain string) (*certificate.Resource, error) {

	if this.legoConfig == nil {
		return nil, errors.New("请先调用 InitLego")
	}

	if !this.HasGetCerts {
		return nil, errors.New("请先获取证书，再更新")
	}

	cert, err := os.ReadFile(this.CertPath)
	if err != nil {
		return nil, err
	}
	key, err := os.ReadFile(this.KeyPath)
	if err != nil {
		return nil, err
	}
	// A client facilitates communication with the CA server.
	client, err := lego.NewClient(this.legoConfig)
	if err != nil {
		return nil, err
	}
	var certRes = certificate.Resource{
		Domain: domain, PrivateKey: key, Certificate: cert,
	}
	res, err := client.Certificate.RenewWithOptions(certRes, &certificate.RenewOptions{})
	if err != nil {
		return nil, err
	}
	return res, err
}

func (this *LegoData) GetCertsByAliDns(domain string, aliDnsKey, aliDnsSecretKey string) (*certificate.Resource, error) {
	if this.legoConfig == nil {
		return nil, errors.New("请先调用 InitLego")
	}
	// This CA URL is configured for a local dev instance of Boulder running in Docker in a VM.
	//config.CADirURL = "http://192.168.99.100:4000/directory"
	//this.legoConfig.CADirURL = lego.LEDirectoryStaging
	this.legoConfig.CADirURL = lego.LEDirectoryProduction
	this.legoConfig.Certificate.KeyType = certcrypto.RSA2048

	// A client facilitates communication with the CA server.
	client, err := lego.NewClient(this.legoConfig)
	if err != nil {
		return nil, err
	}

	dnsConfig := alidns.NewDefaultConfig()
	dnsConfig.APIKey = aliDnsKey
	dnsConfig.SecretKey = aliDnsSecretKey
	dnsProviderCfg, err := alidns.NewDNSProviderConfig(dnsConfig)
	err = client.Challenge.SetDNS01Provider(dnsProviderCfg)
	if err != nil {
		return nil, err
	}
	// New users will need to register
	reg, err := client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
	if err != nil {
		return nil, err
	}
	this.myUser.Registration = reg

	request := certificate.ObtainRequest{
		Domains: []string{domain},
		Bundle:  true,
	}
	certificates, err := client.Certificate.Obtain(request)
	if err != nil {
		return nil, err
	}
	// Each certificate comes back with the cert bytes, the bytes of the client's
	// private key, and a certificate URL. SAVE THESE TO DISK.
	// ... all done.
	this.HasGetCerts = true
	return certificates, nil

}

func (this *LegoData) SaveCerts(cs *certificate.Resource) error {
	err := os.WriteFile(this.CertPath, cs.Certificate, 0777)
	if err != nil {
		return err
	}
	err = os.WriteFile(this.KeyPath, cs.PrivateKey, 0777)
	if err != nil {
		return err
	}
	return nil
}
